<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="BOM编号" prop="bomCode">
        <el-input
          v-model="queryParams.bomCode"
          placeholder="请输入BOM编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="BOM名称" prop="bomName">
        <el-input
          v-model="queryParams.bomName"
          placeholder="请输入BOM名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="产品ID" prop="productId">
        <el-input
          v-model="queryParams.productId"
          placeholder="请输入产品ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="产品" prop="productId">
        <el-select
          v-model="queryParams.productId"
          placeholder="请选择产品"
          clearable
          @keyup.enter="handleQuery"
        >
          <el-option
            v-for="item in productOptions"
            :key="item.productId"
            :label="item.productName"
            :value="item.productId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="BOM类型" prop="bomType">
        <el-select v-model="queryParams.bomType" placeholder="请选择BOM类型" clearable>
          <el-option
            v-for="dict in bom_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="版本号" prop="version">
        <el-input
          v-model="queryParams.version"
          placeholder="请输入版本号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in bom_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['pm:bom:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['pm:bom:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['pm:bom:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['pm:bom:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="bomList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="BOM ID" align="center" prop="bomId" />
      <el-table-column label="BOM编号" align="center" prop="bomCode" />
      <el-table-column label="BOM名称" align="center" prop="bomName" />
      <!-- <el-table-column label="产品ID" align="center" prop="productId" /> -->
      <el-table-column label="产品" align="center" prop="productName" />
      <el-table-column label="BOM类型" align="center" prop="bomType">
        <template #default="scope">
          <dict-tag :options="bom_type" :value="scope.row.bomType"/>
        </template>
      </el-table-column>
      <el-table-column label="版本号" align="center" prop="version" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="bom_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['pm:bom:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['pm:bom:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 引入物料选择器组件 -->
    <MaterialSelector 
      ref="materialSelectorRef" 
      v-model:visible="materialSelectorVisible" 
      @select="handleMaterialSelected" 
    />

    <!-- 添加或修改BOM对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="bomRef" :model="form" :rules="rules" label-width="100px" :inline="true">
        <el-row gutter='20'>
          <el-col :span="12">
            <el-form-item label="BOM编号" prop="bomCode">
          <el-input v-model="form.bomCode" placeholder="请输入BOM编号" disabled/>
        </el-form-item>
          </el-col>
          <el-col span="12">
            <el-form-item label="BOM名称" prop="bomName">
          <el-input v-model="form.bomName" placeholder="请输入BOM名称" />
        </el-form-item>
          </el-col>
          <el-col span="12">
            <el-form-item label="产品" prop="productId">
          <el-select v-model="form.productId" placeholder="请选择产品" filterable clearable>
            <el-option
              v-for="item in productOptions"
              :key="item.productId"
              :label="item.productName"
              :value="item.productId"
            />
          </el-select>
        </el-form-item>
          </el-col>
          <el-col span="12">
            <el-form-item label="BOM类型" prop="bomType">
          <el-select v-model="form.bomType" placeholder="请选择BOM类型">
            <el-option
              v-for="dict in bom_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
          </el-col>
          <el-col span="12">
            <el-form-item label="版本号" prop="version">
              <el-input v-model="form.version" placeholder="请输入版本号" />
            </el-form-item>
          </el-col>
          <el-col span="12">
            <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option
              v-for="dict in bom_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
          </el-col>
          <el-col span="24">
            <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
          </el-row>
        <el-divider content-position="center">BOM明细信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" @click="handleAddBomDetail">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="Delete" @click="handleDeleteBomDetail">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="bomDetailList" :row-class-name="rowBomDetailIndex" @selection-change="handleBomDetailSelectionChange" ref="bomDetail">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="物料" prop="materialId" width="150">
            <template #default="scope">
              <div class="material-selector-container"> 
                <el-input v-model="scope.row.materialName" placeholder="请选择物料" readonly class="material-input" disabled>
                  <template #append>
                    <el-button @click="openMaterialSelector(scope.$index)">选择</el-button>
                  </template>
                </el-input>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="规格型号" prop="specification" width="120">
            <template #default="scope">
              <el-input v-model="scope.row.specification" placeholder="物料规格" readonly disabled />
            </template>
          </el-table-column>
          <el-table-column label="数量" prop="quantity" width="100">
            <template #default="scope">
              <el-input v-model="scope.row.quantity" placeholder="请输入数量" />
            </template>
          </el-table-column>
          <el-table-column label="单位" prop="unit" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.unit" placeholder="请输入单位" disabled/>
            </template>
          </el-table-column>
          <el-table-column label="是否关键物料" prop="isKeyMaterial" width="150">
            <template #default="scope">
              <el-select v-model="scope.row.isKeyMaterial" placeholder="请选择" clearable>
                <el-option
                  v-for="dict in bom_detail_material"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Bom">
import { listBom, getBom, delBom, addBom, updateBom ,listProduct} from "@/api/pm/bom";
import { getMaterial } from "@/api/mwm/material";
import MaterialSelector from "@/components/MaterialSelector/index.vue";

const { proxy } = getCurrentInstance();
const { bom_type, bom_status, bom_detail_material } = proxy.useDict('bom_type', 'bom_status', 'bom_detail_material');

const bomList = ref([]);
const productOptions = ref([]); // 产品下拉框选项
const bomDetailList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const checkedBomDetail = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const materialSelectorVisible = ref(false);
const materialSelectorRef = ref(null);
const currentEditingIndex = ref(-1);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    bomCode: null,
    bomName: null,
    productId: null,
    bomType: null,
    version: null,
    status: null,
  },
  rules: {
    bomCode: [
      { required: true, message: "BOM编号不能为空", trigger: "blur" }
    ],
    bomName: [
      { required: true, message: "BOM名称不能为空", trigger: "blur" }
    ],
    productId: [
      { required: true, message: "产品ID不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询BOM列表 */
function getList() {
  loading.value = true;
  listBom(queryParams.value).then(response => {
    bomList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    bomId: null,
    bomCode: null,
    bomName: null,
    productId: null,
    bomType: null,
    version: null,
    status: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null
  };
  bomDetailList.value = [];
  proxy.resetForm("bomRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.bomId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  // 在前端生成BOM编号
  form.value.bomCode = generateBomCodeLocal();
  open.value = true;
  title.value = "添加BOM";
}

// 在前端生成BOM编号的函数
function generateBomCodeLocal() {
  // 获取当前日期
  const date = new Date();
  const year = date.getFullYear();
  // 月份需要+1且保证两位数格式
  const month = (date.getMonth() + 1).toString().padStart(2, '0');
  const day = date.getDate().toString().padStart(2, '0');
  
  // 生成4位随机数作为序列号
  const randomNum = Math.floor(1000 + Math.random() * 9000);
  
  // 组合BOM编号：BOM + 年月日 + 随机序列号
  return `BOM${year}${month}${day}${randomNum}`;
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _bomId = row.bomId || ids.value
  getBom(_bomId).then(response => {
    form.value = response.data;
    bomDetailList.value = response.data.bomDetailList;
    
    // 处理明细，确保物料名称和编码的显示
    if (bomDetailList.value && bomDetailList.value.length > 0) {
      bomDetailList.value.forEach(detail => {
        // 如果没有物料名称，但有物料ID，可以考虑调用API获取物料信息
        if (!detail.materialName && detail.materialId) {
          // 这里可以根据需要调用获取物料详情的API
          getMaterial(detail.materialId).then(res => {
            detail.materialName = res.data.materialName;
            detail.materialCode = res.data.materialCode;
            detail.specification = res.data.specification; // 获取规格信息
            if (!detail.unit && res.data.unit) {
              detail.unit = res.data.unit;
            }
          }).catch(() => {
            // 出错时使用简单的默认值
            detail.materialName = `物料ID: ${detail.materialId}`;
          });
        }
      });
    }
    
    open.value = true;
    title.value = "修改BOM";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["bomRef"].validate(valid => {
    if (valid) {
      // 清理bomDetailList中的每一项，只保留需要提交的字段
      const detailsToSubmit = bomDetailList.value.map(item => {
        return {
          detailId: item.detailId,
          bomId: item.bomId,
          materialId: item.materialId,
          quantity: item.quantity,
          unit: item.unit,
          isKeyMaterial: item.isKeyMaterial,
          remark: item.remark
          // 注意这里不包含specification字段，因为它是从物料表中获取的，不需要存储在BOM明细表中
        };
      });
      
      form.value.bomDetailList = detailsToSubmit;
      
      if (form.value.bomId != null) {
        updateBom(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addBom(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _bomIds = row.bomId || ids.value;
  proxy.$modal.confirm('是否确认删除BOM编号为"' + _bomIds + '"的数据项？').then(function() {
    return delBom(_bomIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** BOM明细序号 */
function rowBomDetailIndex({ row, rowIndex }) {
  row.index = rowIndex + 1;
}

/** BOM明细添加按钮操作 */
function handleAddBomDetail() {
  let obj = {};
  obj.materialId = "";
  obj.materialName = "";
  obj.materialCode = "";
  obj.specification = ""; // 添加规格字段
  obj.quantity = "";
  obj.unit = "";
  obj.isKeyMaterial = "";
  obj.remark = "";
  bomDetailList.value.push(obj);
}

/** BOM明细删除按钮操作 */
function handleDeleteBomDetail() {
  if (checkedBomDetail.value.length == 0) {
    proxy.$modal.msgError("请先选择要删除的BOM明细数据");
  } else {
    const bomDetails = bomDetailList.value;
    const checkedBomDetails = checkedBomDetail.value;
    bomDetailList.value = bomDetails.filter(function(item) {
      return checkedBomDetails.indexOf(item.index) == -1
    });
  }
}

/** 复选框选中数据 */
function handleBomDetailSelectionChange(selection) {
  checkedBomDetail.value = selection.map(item => item.index)
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('pm/bom/export', {
    ...queryParams.value
  }, `bom_${new Date().getTime()}.xlsx`)
}

// 打开物料选择器
function openMaterialSelector(index) {
  currentEditingIndex.value = index;
  materialSelectorRef.value.open();
  materialSelectorVisible.value = true;
}

// 处理物料选择事件
function handleMaterialSelected(material) {
  if (material && currentEditingIndex.value !== -1) {
    // 获取当前编辑的明细行
    const currentDetail = bomDetailList.value[currentEditingIndex.value];
    
    // 更新物料信息
    currentDetail.materialId = material.materialId;
    currentDetail.materialName = material.materialName;
    currentDetail.materialCode = material.materialCode;
    currentDetail.specification = material.specification; // 添加规格信息
    
    // 如果物料有默认单位，自动填充
    if (material.unit) {
      currentDetail.unit = material.unit;
    }
    
    // 重置当前编辑索引
    currentEditingIndex.value = -1;
  }
}

// 在组件挂载时获取数据
onMounted(() => {
  // 获取产品列表
  listProduct().then(response => {
    productOptions.value = response.data; // 根据你的接口返回结构调整
  });

  getList(); // 原有的获取bom列表
});

</script>

<style scoped>
.material-selector-container {
  display: flex;
  align-items: center;
  width: 100%;
}

.material-input {
  width: 100%;
}
</style>
